package com.catena.web.controller;

import com.catena.mock.core.ScanProjectContext;
import com.catena.web.websocket.MyWebSocket;
import com.catena.web.websocket.NoticeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;

/**
 * Created by hx-pc on 16-3-21.
 */
@Controller
@RequestMapping (value = "/api")
public class CatenaConfigController {

    @Autowired
    private ScanProjectContext scanProjectContext;

    @RequestMapping (value = {"/{target}", "/{2nd}/{target}", "/{2nd}/{3nd}/{target}", "/{2nd}/{3nd}/{4th}/{target}"}, method = RequestMethod.GET)
    public String singleGet(@PathVariable String target) throws IOException {
        return getTargetIndex(target.split("\\."));
    }

    @RequestMapping (value = {"/{target}", "/{2nd}/{target}", "/{2nd}/{3nd}/{target}", "/{2nd}/{3nd}/{4th}/{target}"}, method = RequestMethod.POST)
    public String singlePost(@PathVariable String target) throws IOException {
        return getTargetIndex(target.split("\\."));
    }

    @RequestMapping (value = {"/{target}", "/{2nd}/{target}", "/{2nd}/{3nd}/{target}", "/{2nd}/{3nd}/{4th}/{target}"}, method = RequestMethod.PUT)
    public String singlePut(@PathVariable String target) throws IOException {
        return getTargetIndex(target.split("\\."));
    }

    @RequestMapping (value = {"/{target}", "/{2nd}/{target}", "/{2nd}/{3nd}/{target}", "/{2nd}/{3nd}/{4th}/{target}"}, method = RequestMethod.DELETE)
    public String singleDelete(@PathVariable String target) throws IOException {
        return getTargetIndex(target.split("\\."));
    }

    private String getTargetIndex(String... target) {
        return target[target.length - 1];
    }

    @RequestMapping (value = {"/{project}/init"}, method = RequestMethod.GET)
    public String init(@PathVariable String project, Model model) throws IOException {
        model.addAttribute("project", project);
        return "project";
    }

    @RequestMapping (value = {"/init"}, method = RequestMethod.GET)
    public String init(Model model) throws IOException {
        model.addAttribute("projects", Arrays.asList(scanProjectContext.getProjects()));
        return "init";
    }
}
